<template>
	<div class="data-processing">
		<div class="processing-header">
			<h3>数据处理</h3>
			<div class="processing-info">
				<!-- <el-tag type="info">有效数据行数: {{ props.excelData.length }}</el-tag> -->
			</div>
		</div>

		<div class="processing-operation">
			<el-card>
				<template #header>
					<div class="card-header">
						<span>数据校验与处理</span>
						<div>
							<el-button
								type="primary"
								@click="processData"
								:loading="processing"
								:disabled="processing"
							>
								开始处理
							</el-button>
							<el-button type="info" @click="refreshProcessing" :disabled="processing"
								>刷新</el-button
							>
						</div>
					</div>
				</template>

				<div class="import-options" v-if="processingStep === 0">
					<h4>导入选项</h4>
					<el-form :model="importOptions" label-width="180px">
						<el-form-item label="导入类型">
							<el-radio-group v-model="importOptions.importType">
								<el-radio label="new">新增记录</el-radio>
								<!-- <el-radio label="update">更新记录</el-radio> -->
							</el-radio-group>
						</el-form-item>

						<el-form-item label="学年" style="width: 25%">
							<el-select v-model="importOptions.academicYear" placeholder="请选择学年">
								<el-option
									v-for="year in academicYearOptions"
									:key="year.value"
									:label="year.label"
									:value="year.value"
								/>
							</el-select>
						</el-form-item>

						<el-form-item label="班级" style="width: 45%">
							<el-select
								v-model="importOptions.classId"
								placeholder="请选择班级"
								filterable
								@change="handleClassChange"
							>
								<el-option
									v-for="item in classOptions"
									:key="item.value"
									:label="item.label"
									:value="item.value"
								/>
							</el-select>
						</el-form-item>

						<el-form-item label="成绩类型" style="width: 25%">
							<el-select v-model="importOptions.examType" placeholder="请选择成绩类型">
								<!-- <el-option label="期中成绩" value="midterm" />
								<el-option label="期末成绩" value="final" />
								<el-option label="平时成绩" value="usual" /> -->
								<el-option label="总评成绩" value="total" />
							</el-select>
						</el-form-item>
					</el-form>
				</div>

				<div class="processing-status">
					<el-steps :active="processingStep" finish-status="success" simple>
						<el-step title="选择选项" />
						<el-step title="数据验证" />
						<el-step title="用户匹配" />
						<el-step title="科目匹配" />
						<!-- <el-step title="数据转换" /> -->
					</el-steps>
				</div>

				<div class="processing-details">
					<div v-if="processingStep === 0">
						<el-alert type="info" show-icon :closable="false">
							点击"开始处理"按钮开始校验数据
						</el-alert>
					</div>

					<div v-if="processingStep >= 1">
						<el-alert v-if="validationErrors.length > 0" type="error" show-icon :closable="false">
							数据验证发现以下问题:
							<ul class="error-list">
								<li v-for="(error, index) in validationErrors" :key="index">{{ error }}</li>
							</ul>
						</el-alert>
						<el-alert v-else type="success" show-icon :closable="false"> 数据验证通过 </el-alert>
					</div>

					<div v-if="processingStep >= 2">
						<el-alert v-if="userMatchErrors.length > 0" type="warning" show-icon :closable="false">
							以下学生信息在系统中未找到匹配记录:
							<ul class="error-list">
								<li v-for="(error, index) in userMatchErrors" :key="index">{{ error }}</li>
							</ul>
						</el-alert>
						<el-alert v-else type="success" show-icon :closable="false">
							所有学生信息匹配成功
						</el-alert>
					</div>

					<div v-if="processingStep >= 3">
						<el-alert v-if="!allSubjectsMatched" type="warning" show-icon :closable="false">
							存在未匹配的科目，请确保所有科目都已匹配后再继续
						</el-alert>
						<el-alert v-else type="success" show-icon :closable="false">
							所有科目匹配成功，数据格式转换完成
						</el-alert>
					</div>

					<div v-if="processingStep >= 4">
						<el-alert type="success" show-icon :closable="false">
							数据处理完成，可以进入下一步进行导入确认
						</el-alert>
					</div>
				</div>

				<div class="action-buttons">
					<el-button @click="goBack">返回上一步</el-button>
					<el-button type="primary" @click="confirmProcessing" :disabled="!canProceed">
						进入导入确认
					</el-button>
				</div>
			</el-card>
		</div>

		<div class="tables-container" v-if="processingStep > 0">
			<div class="tables-row">
				<div class="table-left">
					<h4>
						用户匹配状态（学生
						<span style="color: brown"> {{ processedData.filter((r) => r.matched).length }} </span
						>名）
					</h4>
					<el-table
						v-loading="processing"
						:data="processedData"
						border
						stripe
						style="width: 100%"
						height="400px"
						:header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
					>
						<el-table-column type="index" label="序号" width="60" />
						<el-table-column prop="studentId" label="学号" min-width="120" />
						<el-table-column prop="name" label="姓名" min-width="90" />
						<el-table-column label="用户匹配状态" width="120">
							<template #default="scope">
								<el-tag :type="scope.row.matched ? 'success' : 'danger'">
									{{ scope.row.matched ? '已匹配' : '未匹配' }}
								</el-tag>
							</template>
						</el-table-column>
					</el-table>
				</div>

				<div class="table-right">
					<h4>
						科目匹配状态（科目
						<span style="color: brown">
							{{ matchedSubjects.filter((s) => s.isMatched).length }} </span
						>门）
					</h4>
					<el-table
						:data="matchedSubjects"
						border
						stripe
						style="width: 100%"
						height="400px"
						:header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
					>
						<el-table-column type="index" label="序号" width="60" />
						<el-table-column prop="subjectName" label="Excel中的科目名" min-width="140" />
						<!-- <el-table-column prop="matchedName" label="系统中对应科目" min-width="140" /> -->
						<el-table-column label="匹配状态" width="100">
							<template #default="scope">
								<el-tag :type="scope.row.isMatched ? 'success' : 'warning'">
									{{ scope.row.isMatched ? '已匹配' : '未匹配' }}
								</el-tag>
							</template>
						</el-table-column>
					</el-table>
				</div>
			</div>
			<!-- 
			<div class="tables-row" v-if="processingStep >= 3 && transformedScoreData.length > 0">
				<div class="table-full">
					<div style="display: flex">
						<h4>
							转换后的成绩数据共
							<span style="color: blueviolet">
								{{ transformedScoreData.length }}
							</span>
							条
						</h4>
					</div>
					<el-table
						:data="transformedScoreData"
						border
						stripe
						style="width: 100%"
						height="400px"
						:header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
					>
						<el-table-column type="index" label="序号" width="60" />
						<el-table-column label="学年" width="120" prop="academicYear" />
						<el-table-column label="班级" min-width="220" prop="classname" />
						<el-table-column label="姓名" min-width="60">
						</el-table-column>
						<el-table-column label="学号" min-width="80" prop="_original.studentId" />
						<el-table-column label="科目" min-width="120" prop="_original.subjectName" />
						<el-table-column label="理论成绩" width="80">
						</el-table-column>
						<el-table-column label="理论状态" width="90">
							<template #default="scope">
								<el-tag :type="scope.row.aboutTheory === 'normal' ? 'success' : 'warning'">
									{{
										scope.row.aboutTheory === 'normal'
											? '正常'
											: scope.row.aboutTheory === 'absent'
												? '缺考'
												: scope.row.aboutTheory === 'violation'
													? '作弊'
													: '未知'
									}}
								</el-tag>
							</template>
						</el-table-column>
						<el-table-column label="实践成绩" width="80">
						</el-table-column>
						<el-table-column label="实践状态" width="90">
							<template #default="scope">
								<el-tag :type="scope.row.aboutPractice === 'normal' ? 'success' : 'warning'">
									{{
										scope.row.aboutPractice === 'normal'
											? '正常'
											: scope.row.aboutPractice === 'absent'
												? '缺考'
												: scope.row.aboutPractice === 'violation'
													? '作弊'
													: '未知'
									}}
								</el-tag>
							</template>
						</el-table-column>
						<el-table-column label="成绩类型" width="100">
							<template #default="scope">
								<el-tag type="info">
									{{
										importOptions.examType === 'final'
											? '期末成绩'
											: importOptions.examType === 'midterm'
												? '期中成绩'
												: importOptions.examType === 'usual'
													? '平时成绩'
													: '总评成绩'
									}}
								</el-tag>
							</template>
						</el-table-column>
					</el-table>
					<div class="data-summary" v-if="transformedScoreData.length > 10"></div>
				</div>
			</div> -->
		</div>
	</div>
</template>

<script lang="ts" setup>
import { ref, computed, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { getClassnameListService } from '@/api/education/classname'
import { getUserListByClassIdListService } from '@/api/user_classname'
import { getSubjectListService } from '@/api/education/subject'
import { useUserStore } from '@/stores/modules/user'

const props = defineProps<{
	excelData: any[]
	headers: string[]
}>()

const emit = defineEmits(['processing-confirmed', 'go-back'])

// 处理状态
const processing = ref(false)
const processingStep = ref(0)
const validationErrors = ref<string[]>([])
const userMatchErrors = ref<string[]>([])

// 处理后的数据
const processedData = ref<any[]>([])

// 是否可以进入下一步
const canProceed = computed(() => {
	return processingStep.value === 4 && processedData.value.length > 0 && allSubjectsMatched.value
})

// 获取当前学年
const getCurrentAcademicYear = () => {
	const now = new Date()
	const year = now.getFullYear()
	const month = now.getMonth() + 1

	// 如果当前月份大于8月，则为当前年份-下一年份学年
	// 否则为上一年份-当前年份学年
	if (month >= 9) {
		return `${year}-${year + 1}`
	} else {
		return `${year - 1}-${year}`
	}
}

// 导入选项
const importOptions = ref({
	importType: 'new', // 导入类型: new-新增, update-更新
	subjectId: '', // 学科ID
	classId: '', // 班级ID
	// academicYear: getCurrentAcademicYear(), // 默认使用当前学年
	academicYear: '2023-2024',
	examType: 'total', // 成绩类型
	remark: '' // 备注
})

// 班级中的学生数据
const classStudents = ref<any[]>([])

// 班级选项
const classOptions = ref([{ value: '', label: '' }])

// 班级改变时获取对应的学生数据
const handleClassChange = () => {
	// 根据班级ID获取学生数据
	getClassStudents()
}

// 获取班级学生
const getClassStudents = async () => {
	const res = await getUserListByClassIdListService(1, [Number(importOptions.value.classId)])

	if (res.data.code === 1 && res.data.data) {
		classStudents.value = res.data.data.map((student: any) => ({
			id: student.userId,
			studentId: student.typeNumber,
			name: student.uname
		}))
	} else {
		ElMessage.error('获取班级学生数据失败')
		classStudents.value = []
	}
}

// // 过滤指定数据
// const validData = computed(() => {
// 	return props.excelData.filter((row) => {
// 		if (!row) return false

// 		// 检查是否是签名行或空行
// 		const values = Object.values(row)
// 		const firstValue = String(values[0] || '').trim()

// 		return !firstValue.includes('序号')
// 	})
// })

// // 有效数据总数
// const validDataCount = computed(() => {
// 	return validData.value.length
// })

// 识别学号列
const studentIdColumn = computed(() => {
	return props.headers.find((h) => h.includes('学号')) || ''
})

// 识别姓名列
const nameColumn = computed(() => {
	// 先查找包含"姓名"的列
	let col = props.headers.find((h) => /姓名/.test(h)) || ''

	// 如果没找到，尝试查找序号后的第一列
	if (!col) {
		const indexColumn = props.headers.findIndex((h) => h.includes('序号') || h.includes('序 号'))
		if (indexColumn !== -1 && indexColumn + 1 < props.headers.length) {
			col = props.headers[indexColumn + 1]
		}
	}

	return col
})

// 识别成绩列
const scoreColumns = computed(() => {
	const studentIdIdx = props.headers.findIndex((h) => h.includes('学号'))

	// 如果找不到学号列，返回空数组
	if (studentIdIdx === -1) return []

	// 返回学号列之后的所有列
	return props.headers.slice(studentIdIdx + 1).filter((h) => h !== nameColumn.value)
})
// console.log(scoreColumns.value)

// 从成绩列中提取科目名称
const extractedSubjects = computed(() => {
	const subjects = new Set<string>()

	scoreColumns.value.forEach((column) => {
		let subjectName = column
		let examType = '理论' // 默认为理论考试

		// 处理有理论/实践后缀的科目名
		if (column.includes('-理论')) {
			subjectName = column.split('-理论')[0]
			examType = '理论'
		} else if (column.includes('-实践')) {
			subjectName = column.split('-实践')[0]
			examType = '实践'
		} else if (column.includes('_理论')) {
			subjectName = column.split('_理论')[0]
			examType = '理论'
		} else if (column.includes('_实践')) {
			subjectName = column.split('_实践')[0]
			examType = '实践'
		}
		// 没有后缀的默认为理论考试

		// 如果不是列N格式并且不是空字符串，则添加到科目集合
		if (
			!subjectName.startsWith('列') &&
			!subjectName.includes('姓名') &&
			!subjectName.includes('班级') &&
			!subjectName.includes('学号') &&
			subjectName.trim() !== ''
		) {
			subjects.add(subjectName)
		}
	})

	return Array.from(subjects)
})

// 科目数据
const subjectData = ref<any[]>([])

// 匹配系统中的科目与Excel中解析到的科目
const matchedSubjects = computed(() => {
	if (!subjectData.value || subjectData.value.length === 0) {
		return extractedSubjects.value.map((subject) => ({
			subjectName: subject,
			matchedName: '未找到匹配',
			isMatched: false,
			subjectId: null
		}))
	}

	return extractedSubjects.value.map((subject) => {
		// 尝试在系统科目中找到完全匹配项，名称必须完全一致
		const matchedSubject = subjectData.value.find((item) => item.subject === subject)

		return {
			subjectName: subject,
			matchedName: matchedSubject ? matchedSubject.subject : '未找到匹配',
			isMatched: !!matchedSubject,
			subjectId: matchedSubject?.id
		}
	})
})

// 检查是否所有科目都已匹配
const allSubjectsMatched = computed(() => {
	// 如果没有提取到科目，默认为已匹配（避免空数据情况下无法继续）
	if (extractedSubjects.value.length === 0) return true

	// 检查是否有未匹配的科目
	return matchedSubjects.value.every((subject) => subject.isMatched)
})

// 特殊成绩值映射
const specialScores = {
	缓考: 'absent',
	缺考: 'absent',
	作弊: 'violation',
	免修: 'absent',
	免考: 'absent',
	舞弊: 'violation',
	违纪: 'violation'
}

// 反向特殊成绩值映射
const specialScoresReverse: Record<string, string> = {
	absent: '缺考',
	violation: '作弊'
}

// 检查是否是特殊成绩
const isSpecialScore = (score: any) => {
	if (typeof score === 'string' && (score === 'absent' || score === 'violation')) {
		return true
	}
	return false
}

// 获取特殊成绩文本
const getSpecialScoreText = (score: string) => {
	return specialScoresReverse[score] || score
}

// 获取科目数据
const getSubjectData = async () => {
	try {
		const res = await getSubjectListService()
		if (res.data.code === 1 && res.data.data) {
			subjectData.value = res.data.data
		}
	} catch (error) {
		console.error('获取科目列表失败', error)
	}
}

// 获取用户信息
const userStore = useUserStore()

// 开始数据处理
const processData = async () => {
	// 验证表单完整性
	if (!importOptions.value.classId || !importOptions.value.examType) {
		ElMessage.warning('请填写完整的导入选项')
		return
	}

	if (processing.value) return

	processing.value = true
	processingStep.value = 1
	validationErrors.value = []
	userMatchErrors.value = []

	try {
		// 获取科目数据
		await getSubjectData()

		// 步骤1: 数据验证
		await validateData()

		// 步骤2: 用户匹配
		await matchUsers()

		// 步骤3: 科目匹配
		await matchSubjects()

		// 执行数据转换
		await transformData()

		// 步骤4: 完成处理
		processingStep.value = 4
		ElMessage.success('数据处理完成')
	} catch (error: any) {
		ElMessage.error(`数据处理出错: ${error.message}`)
		console.error('数据处理错误:', error)
	} finally {
		processing.value = false
	}
}

// 数据验证
const validateData = async () => {
	// 模拟异步验证过程
	await new Promise((resolve) => setTimeout(resolve, 500))

	validationErrors.value = []

	// 检查必要列是否存在
	if (!studentIdColumn.value) {
		validationErrors.value.push('缺少学号列')
	}

	if (!nameColumn.value) {
		validationErrors.value.push('缺少姓名列')
	}

	if (scoreColumns.value.length === 0) {
		validationErrors.value.push('缺少成绩列')
	}

	// 验证每行数据
	props.excelData.forEach((row, index) => {
		// 验证学号
		if (studentIdColumn.value && !row[studentIdColumn.value]) {
			validationErrors.value.push(`第 ${index + 1} 行: 学号不能为空`)
		}

		// 验证姓名
		if (nameColumn.value && !row[nameColumn.value]) {
			validationErrors.value.push(`第 ${index + 1} 行: 姓名不能为空`)
		}
	})

	// 开始处理数据
	const processed = props.excelData.map((row) => {
		const result: any = {
			studentId: studentIdColumn.value ? row[studentIdColumn.value] : '',
			name: nameColumn.value ? row[nameColumn.value] : '',
			matched: false,
			matchId: null
		}

		// 加入成绩列
		scoreColumns.value.forEach((column) => {
			let score = row[column]

			// 处理特殊情况成绩
			if (typeof score === 'string' && Object.keys(specialScores).includes(score.trim())) {
				score = specialScores[score.trim() as keyof typeof specialScores]
			}

			result[column] = score
		})

		console.log(result)
		return result
	})

	processedData.value = processed

	// 如果没有错误，进入下一步
	if (validationErrors.value.length === 0) {
		processingStep.value = 1
	}
}

// 用户匹配
const matchUsers = async () => {
	// 模拟异步用户匹配过程
	await new Promise((resolve) => setTimeout(resolve, 800))

	userMatchErrors.value = []

	// 如果没有选择班级，无法匹配学生
	if (!importOptions.value.classId) {
		userMatchErrors.value.push('请先选择班级')
		return
	}

	// 如果班级学生为空，尝试重新获取
	if (classStudents.value.length === 0) {
		await getClassStudents()
	}

	// 匹配学生信息
	processedData.value.forEach((row, index) => {
		const match = classStudents.value.find(
			(student) => student.studentId === row.studentId && student.name === row.name
		)

		if (match) {
			row.matched = true
			row.matchId = match.id
		} else {
			row.matched = false
			userMatchErrors.value.push(
				`第 ${index + 1} 行: 学号"${row.studentId}" 姓名"${row.name}"在所选班级中未找到`
			)
		}
	})

	processingStep.value = 2
}

// 科目匹配
const matchSubjects = async () => {
	// 模拟异步数据转换过程
	await new Promise((resolve) => setTimeout(resolve, 600))

	// 检查科目是否全部匹配
	if (allSubjectsMatched.value) {
		processingStep.value = 3
	} else {
		// 如果有科目未匹配，提示用户
		ElMessage.warning('有科目未在系统中找到匹配，请检查')
		processingStep.value = 3
	}
}

// 存储转换后的数据
const transformedScoreData = ref<any[]>([])

// 数据转换
const transformData = async () => {
	// 模拟异步数据转换过程
	await new Promise((resolve) => setTimeout(resolve, 600))

	// 用于统计错误信息
	const stats = {
		totalStudents: processedData.value.length,
		matchedStudents: processedData.value.filter((row) => row.matched).length,
		totalSubjects: matchedSubjects.value.length,
		matchedSubjects: matchedSubjects.value.filter((subject) => subject.isMatched).length,
		missingScores: 0
	}

	// 获取当前班级信息
	const className = getClassName()

	// 将处理后的数据转换为后端所需的格式
	const transformed = processedData.value
		.filter((row) => row.matched) // 只处理匹配到的学生数据
		.flatMap((row) => {
			// 每个学生对应多个科目的成绩记录
			return matchedSubjects.value
				.filter((subject) => subject.isMatched) // 只处理匹配到的科目
				.map((subject) => {
					// 科目名称
					const subjectName = subject.subjectName
					// 尝试找到理论和实践成绩列
					const theoryColumnName = scoreColumns.value.find(
						(colName) =>
							colName === subjectName ||
							colName === `${subjectName}-理论` ||
							colName === `${subjectName}_理论`
					)
					const practiceColumnName = scoreColumns.value.find(
						(colName) => colName === `${subjectName}-实践` || colName === `${subjectName}_实践`
					)

					// 获取理论和实践成绩
					let theoryScore = theoryColumnName ? row[theoryColumnName] : null
					let practiceScore = practiceColumnName ? row[practiceColumnName] : null

					// 如果只有科目名没有后缀，且没有找到带后缀的列，则该成绩视为理论成绩
					if (!theoryColumnName && !practiceColumnName) {
						const plainColumnName = scoreColumns.value.find((colName) => colName === subjectName)
						if (plainColumnName) {
							theoryScore = row[plainColumnName]
						} else {
							stats.missingScores++
							console.log(
								`未找到科目"${subjectName}"的任何成绩列，学生: ${row.name}(${row.studentId})`
							)
						}
					}

					// 检查理论成绩是否为特殊成绩
					const aboutTheory = isSpecialScore(theoryScore)
						? getSpecialScoreAboutStatus(theoryScore)
						: 'normal'

					// 检查实践成绩是否为特殊成绩
					const aboutPractice = isSpecialScore(practiceScore)
						? getSpecialScoreAboutStatus(practiceScore)
						: 'normal'

					// 构建成绩数据对象（按照后端要求的格式）
					const scoreData: any = {
						// 基本信息
						studentId: row.matchId, // 使用系统中匹配到的学生ID
						classId: Number(importOptions.value.classId),
						subjectId: subject.subjectId,
						radioId: 1, // 默认为1
						judgeId: userStore.userInfo.userInfo.userId || 0, // 当前登录用户ID
						academicYear: importOptions.value.academicYear, // 使用选择的学年

						// 理论相关
						midTermTheory: null,
						finalTheory: null,
						usualTheory: null,
						aboutTheory: aboutTheory,

						// 实践相关
						midTermPractice: null,
						finalPractice: null,
						usualPractice: null,
						aboutPractice: aboutPractice,

						// 总分
						theoryTotal: null,
						practiceTotal: null
					}

					// 根据成绩类型设置对应的字段
					if (importOptions.value.examType === 'final') {
						scoreData.finalTheory = aboutTheory !== 'normal' ? null : Number(theoryScore) || null
						scoreData.finalPractice =
							aboutPractice !== 'normal' ? null : Number(practiceScore) || null
					} else if (importOptions.value.examType === 'midterm') {
						scoreData.midTermTheory = aboutTheory !== 'normal' ? null : Number(theoryScore) || null
						scoreData.midTermPractice =
							aboutPractice !== 'normal' ? null : Number(practiceScore) || null
					} else if (importOptions.value.examType === 'usual') {
						scoreData.usualTheory = aboutTheory !== 'normal' ? null : Number(theoryScore) || null
						scoreData.usualPractice =
							aboutPractice !== 'normal' ? null : Number(practiceScore) || null
					} else if (importOptions.value.examType === 'total') {
						scoreData.theoryTotal =
							aboutTheory !== 'normal'
								? null
								: theoryScore === null || theoryScore === undefined || theoryScore === ''
									? null
									: Number(theoryScore) || null
						scoreData.practiceTotal =
							aboutPractice !== 'normal'
								? null
								: practiceScore === null || practiceScore === undefined || practiceScore === ''
									? null
									: Number(practiceScore) || null

						// 调试日志
						console.log(`[调试] 科目: ${subjectName}, 学生: ${row.name}`)
						console.log(`[调试] 理论成绩原始值: ${theoryScore}, 转换后: ${scoreData.theoryTotal}`)
						console.log(
							`[调试] 实践成绩原始值: ${practiceScore}, 转换后: ${scoreData.practiceTotal}`
						)
					}

					return {
						...scoreData
					}
				})
		})

	// 更新转换后的数据
	transformedScoreData.value = transformed

	// // 打印统计信息
	// console.log('数据转换统计信息:', stats)
	// console.log('期望的数据量:', stats.matchedStudents * stats.matchedSubjects)
	// console.log('实际转换的数据量:', transformed.length)
	// console.log('转换后的数据样例:', transformed[0])

	processingStep.value = 3
}

// 根据特殊成绩值获取考试状态
const getSpecialScoreAboutStatus = (score: string) => {
	// 已经是状态值，直接返回
	if (score === 'violation' || score === 'absent') {
		return score
	}
	return 'normal'
}

// 刷新数据处理
const refreshProcessing = () => {
	if (processing.value) return

	getClasses()
	processingStep.value = 0
	validationErrors.value = []
	userMatchErrors.value = []
	processedData.value = []
}

// 返回上一步
const goBack = () => {
	emit('go-back')
}

// 确认处理，进入下一步
const confirmProcessing = () => {
	console.log('进入下一步')

	if (!canProceed.value) {
		ElMessage.warning('请先完成数据处理')
		return
	}

	// 准备传递给父组件的数据
	// 直接使用转换后的成绩数据，它已经符合后端要求的格式
	const scoreDataForBackend = transformedScoreData.value.map((score) => {
		const { ...scoreData } = score
		return scoreData
	})

	console.log(scoreDataForBackend)

	// 获取班级名称
	const selectedClass = classOptions.value.find((c) => c.value === importOptions.value.classId)
	const className = selectedClass ? selectedClass.label : ''

	// 获取科目列表名称
	const subjectList = matchedSubjects.value
		.filter((subject) => subject.isMatched)
		.map((subject) => subject.subjectName)

	// 整理选项数据
	const optionsData = {
		dataCount: transformedScoreData.value.length, // 数据数
		academicYear: importOptions.value.academicYear, // 学年
		className: className, // 班级名称
		subjectList: subjectList, // 科目列表
		examType: importOptions.value.examType // 成绩类型
	}

	// 将处理后的数据和导入选项一起传递
	emit('processing-confirmed', {
		scoreData: scoreDataForBackend, // 符合后端格式的数据
		options: optionsData // 精简后的选项数据
	})
}

// 格式化学历
const formatEducation = (education: string) => {
	if (education === 'undergrad') {
		return '本科'
	} else if (education === 'vocEd') {
		return '专科'
	} else {
		return '未知'
	}
}

// 获取班级数据
const getClasses = async () => {
	const res = await getClassnameListService()
	if (res.data.data && res.data.code === 1) {
		classOptions.value = res.data.data.map((item: any) => ({
			value: item.classId,
			label: `${formatEducation(item.level)}${item.academy}${item.major}${item.grade}级${item.classname}班`
		}))
	} else {
		ElMessage.error('获取班级数据失败')
	}
}

// 学年选项
const academicYearOptions = computed(() => {
	const currentYear = new Date().getFullYear()
	let options = []

	// 生成近6年的学年选项
	for (let i = 0; i < 6; i++) {
		const year = currentYear - i
		options.push({
			label: `${year - 1}-${year}`,
			value: `${year - 1}-${year}`
		})
	}

	options = [
		{ label: '2023-2024', value: '2023-2024' },
		{ label: '2022-2023', value: '2022-2023' },
		{ label: '2021-2022', value: '2021-2022' }
	] // 默认选择

	return options
})

// 获取班级名称
const getClassName = () => {
	const selectedClass = classOptions.value.find((c) => c.value === importOptions.value.classId)
	return selectedClass ? selectedClass.label : ''
}

onMounted(() => {
	getClasses()
})
</script>

<style lang="scss" scoped>
.data-processing {
	width: 100%;

	.processing-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 20px;

		h3 {
			margin: 0;
			color: var(--el-text-color-primary);
		}

		.processing-info {
			display: flex;
			gap: 10px;
		}
	}

	.processing-operation {
		margin-bottom: 20px;

		.card-header {
			display: flex;
			justify-content: space-between;
			align-items: center;
		}

		.processing-status {
			margin-bottom: 20px;
		}

		.processing-details {
			margin-top: 20px;

			.error-list {
				margin: 10px 0;
				padding-left: 20px;

				li {
					margin-bottom: 5px;
				}
			}
		}
	}

	.tables-container {
		margin-bottom: 20px;

		h4 {
			margin-top: 0;
			margin-bottom: 15px;
			font-weight: normal;
		}

		.tables-row {
			display: flex;
			gap: 20px;
			margin-bottom: 20px;

			.table-left,
			.table-right {
				flex: 1;
			}

			.table-full {
				width: 100%;
			}

			.data-summary {
				margin-top: 10px;
			}
		}
	}

	.action-buttons {
		display: flex;
		justify-content: center;
		margin-top: 20px;
		gap: 15px;
	}
}
</style>
